﻿using MyHelper;
using MySqlX.XDevAPI.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace weighing
{
    /// <summary>
    /// 备用字段的 Combo Box item source
    /// </summary>

    public class BackupItemsHelper
    {
        #region Instance 
        private static BackupItemsHelper instance;
        public static BackupItemsHelper Instance
        {
            get
            {
                if (instance == null) instance = new BackupItemsHelper();
                return instance;
            }
        }
        #endregion

        public Dictionary<string ,List<string>> LoadFromFile()
        {
            if (!Directory.Exists(Constant.tempPath))
            {
                Directory.CreateDirectory(Constant.tempPath);
            }
            string file = Path.Combine(Constant.tempPath, Constant.BackupFieldItemSourcefile);
            if (!File.Exists(file))
            {
                File.Create(file);
            }
            Thread.Sleep(1000);
            if (!File.Exists(file))
            {
                Log.Error($"文件{false}不存在");               
                return new Dictionary<string, List<string>>();
            }
            string json = FileHelper.Reader(file, Encoding.UTF8);
            if (string.IsNullOrEmpty(json))
            {            
                return new Dictionary<string, List<string>>(); ;
            }
            var data = JsonHelper.JsonToObject<Dictionary<string, List<string>>>(json);
            foreach (KeyValuePair<string, List<string>> entry in data)
            {
                var d = entry.Value;
                d?.RemoveAll((i) => string.IsNullOrEmpty(i?.Trim()));
            }
            return data;
        }


        /// <summary>
        /// 更新 文件
        /// </summary>
        /// <returns></returns>
        public int UpdateToFile(Dictionary<string,List<string>> data)
        {
            try
            {
                FileHelper.FolderExistsCreater(Constant.tempPath);
                String file = Path.Combine(Constant.tempPath, Constant.BackupFieldItemSourcefile);
    
                if (!FileHelper.Exists(file))
                {
                    FileHelper.CreateFile(file);
                }
                foreach (KeyValuePair<string, List<string>> entry in data)
                {
                    var d = entry.Value;
                    d?.RemoveAll((i) => string.IsNullOrEmpty(i?.Trim()));                    
                }
                string json = JsonHelper.ObjectToJson(data);
                FileHelper.Write(file, JsonHelper.FormatJson(json));
                return 1;
            }
            catch (Exception e)
            {
                Log.Error("更新文件失败：" + e.Message, e.StackTrace, true);
                return 0;
            }
        }
    }
}
